(function($, window, document) {
	function compressZip(srcPath, zipPath, callback) {
		var File = plus.android.importClass('java.io.File');
		var ZipUitls = plus.android.importClass('io.dcloud.util.ZipUtils');

		var srcFile = new File(srcPath);
		var zipFile = new File(zipPath);
		var arrayOfFile = [];
		if (srcFile.isDirectory()) {
			arrayOfFile = srcFile.listFiles();
		} else {
			arrayOfFile.push(srcFile);
		}
		ZipUitls.zipFiles(arrayOfFile, zipFile);
		setTimeout(function() {
			callback(arrayOfFile, zipFile);
		}, 1000);
	}

	function loadAppMainJs(jsPath, callBack) {
		window.currentWebview = window.currentWebview || plus.webview.currentWebview();
		window.$app = null;
		currentWebview.appendJsFile(jsPath);
		var intl = self.setInterval(function() {
			if (window.$app) {
				clearInterval(intl)
				var apps = localStorageJson('apps', {});
				apps[name] = $app;
				localStorageJson('apps', apps, true);
				callBack($app);
			}
		}, 50);
	}

	function resetVersion(wgtuDir, callback) {
		wgtuDir.getFile('tmp/www/manifest.json', {}, function(fileEntry) {
			fileEntry.file(function(file) {
				var fileReader = new plus.io.FileReader();
				fileReader.readAsText(file, 'utf-8');
				fileReader.onloadend = function(evt) {
					waiting.setTitle('read success');
					var data = JSON.parse(evt.target.result);
					data.version.name = Date.now() + '';
					fileEntry.createWriter(function(writer) {
						writer.write(JSON.stringify(data));
						writer.onwriteend = function(e) {
							if (plus.os.name == 'Android') {
								compressZip(wgtuDir.fullPath + 'tmp/', wgtuDir.fullPath + 'current.wgtu', function() {
									waiting.setTitle('compress success' + JSON.stringify(arguments));
									callback('_downloads/wgtu/current.wgtu');
								});
							} else {
								plus.zip.compress('_downloads/wgtu/tmp/', '_downloads/wgtu/current.wgtu', function() {
									waiting.setTitle('compress success' + JSON.stringify(arguments));
									callback('_downloads/wgtu/current.wgtu');
								}, function(error) {
									alert("打包失败!" + error.message);
								});
							}
						};
					}, function(e) {
						alert(e.message);
						waiting.close();
					});
				}
				fileReader.onerror = function(error) {
					waiting.setTitle('读取配置错误' + error.message);
				}
			});
		});
	}
	$.installApp = function(name, url, init) {
		plus.runtime.getProperty(plus.runtime.appid, function(inf) {
			console.log(inf.version);
		});
		window.waiting = plus.nativeUI.showWaiting('开始安装 ' + name);
		var dtask = plus.downloader.createDownload(url, {
			method: "GET",
			filename: '_downloads/wgtu/tmp.wgtu'
		}, function(d, status) {
			if (status == 200) {
				waiting.setTitle("解压中...");
				plus.zip.decompress(d.filename, '_downloads/wgtu/tmp/', function() {
					waiting.setTitle("安装中...");
					plus.io.resolveLocalFileSystemURL('_downloads/wgtu/', function(wgtuDir) {
						resetVersion(wgtuDir, function(path) {
							console.log(path);
							plus.runtime.install(path, {
								force: true
							}, function() {
								function clear() {
									waiting.close();
									plus.nativeUI.alert("安装成功, 现在重启?", function() {
										wgtuDir.removeRecursively();
										plus.runtime.restart();
									});
								}
								loadAppMainJs('_downloads/wgtu/tmp/index.js', function(app) {
									if (init) {
										app.install();
									}
									clear();
								});
							}, function(e) {
								plus.nativeUI.closeWaiting();
								alert("Update wgtu failed: " + e.message);
							});
						})
					});
				}, function(error) {
					alert("deCompress error!1" + error.message);
				});
			} else {
				plus.nativeUI.closeWaiting();
				plus.nativeUI.alert('下载失败');
			}
		});
		dtask.addEventListener('statechanged', function(task, status) {
			if (!dtask) {
				return;
			}
			switch (task.state) {
				case 1: // 开始
					waiting.setTitle("正在下载...");
					break;
				case 2: // 已连接到服务器
					waiting.setTitle("链接到服务器...");
					break;
				case 3: // 已接收到数据
					waiting.setTitle("下载数据更新...");
					break;
				case 4: // 下载完成
					waiting.setTitle("下载完成!...");
					break;
			}
		});
		dtask.start();
	}
})(mui, window, document);